//
//  FScrollView.m
//  JoinUser
//
//  Created by xujingjing on 16/6/15.
//  Copyright © 2016年 xujingjing. All rights reserved.
//
#import "FScrollView.h"
#import "UIView+FindNav.h"
#import "OpenUrlVC.h"
#import "UIImageView+WebCache.h"
#define FScrollViewWidth self.frame.size.width
#define FScrollViewHeight self.frame.size.height
@interface FScrollView ()<UIScrollViewDelegate>
{
    UIScrollView *_scrollView;
    UIImageView *_leftImageView;
    UIImageView *_centerImageView;
    UIImageView *_rightImageView;
    UIPageControl *_pageControl;
    NSInteger _currentImageIndex;//当前图片索引
    int _imageCount;//图片总数
    
    NSTimer *_timer;

    
}

@property (nonatomic,strong)NSTimer *time;
@end

@implementation FScrollView

-(instancetype)initWithFrame:(CGRect)frame withimagearry:(NSArray *)images redirectUrl:(NSArray *)redirectUrl
{
    self = [super initWithFrame:frame];
    if (self) {
        self.clipsToBounds = YES;
      _imageData = [NSMutableArray array];
        _Redirect = [NSMutableArray array];

                for (int i=0; i < images.count; i ++) {
                           NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",images[i]]];
                   
                        [_imageData addObject:url];
                    
                    NSURL *urlRedirect=[NSURL URLWithString:[NSString stringWithFormat:@"%@",redirectUrl[i]]];
                    [_Redirect addObject:urlRedirect];


                }
       
        
        _imageCount = (int)images.count;
        //添加滚动控件
        [self addScrollView];
        _timer = [NSTimer scheduledTimerWithTimeInterval:3.0
                                                  target:self
                                                selector:@selector(processTimer)
                                                userInfo:nil repeats:YES] ;
        
        
        
        if (_imageCount == 1) {

        _centerImageView=[[UIImageView alloc]initWithFrame:CGRectMake(FScrollViewWidth, 0, FScrollViewWidth, FScrollViewHeight)];
        _centerImageView.contentMode=UIViewContentModeScaleAspectFit;

        [_centerImageView sd_setImageWithURL:_imageData[0] placeholderImage:DefaultIMG];
        [_scrollView addSubview:_centerImageView];
            
        }else
        {
       
        
        //添加图片控件
        [self addImageViews];
        //添加分页控件
        [self addPageControl];
        //加载默认图片
        [self setDefaultImage];
            
            [self add_backBtn];
        }
      
    }
    return self;
}


-(void)add_backBtn{
    
    _back =[UIButton buttonWithType:UIButtonTypeCustom];
    _back.hidden = YES;
    _back.frame = CGRectMake(10, 30, 20, 20);
    [_back setImage:[UIImage imageNamed:@"首页_线路分类_03"] forState:UIControlStateNormal];
    [_back setTitle:@"" forState:UIControlStateNormal];
    [_back setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_back addTarget:self action:@selector(_back) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_back];
    
}
-(void)_back{
    [self.navgationController popViewControllerAnimated:YES];

}
-(void)loadImageWithArr:(NSArray *)newBannerImgArr RedicreArr:(NSArray *)redicreArr{
   
    [_imageData removeAllObjects];
    [_Redirect removeAllObjects];
  //  if (redicreArr.count>=newBannerImgArr.count) {
        
        for (int i=0; i < newBannerImgArr.count; i ++) {
            NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",newBannerImgArr[i]]];
            NSURL *urlRedicre=[NSURL URLWithString:[NSString stringWithFormat:@"%@",redicreArr[i]]];
            
            [_imageData addObject:url];
            [_Redirect addObject:urlRedicre];
            
            
    //    }
        
    }
    
    
    




}

-(void)processTimer{
    
    [_scrollView setContentOffset:CGPointMake(2 *CGRectGetWidth(_scrollView.bounds),0) animated:YES];
    
    
}

#pragma mark 加载图片数据


#pragma mark 添加控件
-(void)addScrollView{
    _scrollView=[[UIScrollView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self addSubview:_scrollView];
    //设置代理
    _scrollView.delegate=self;
    //设置contentSize
    _scrollView.contentSize=CGSizeMake(3*FScrollViewWidth, FScrollViewHeight) ;
    //设置当前显示的位置为中间图片
    [_scrollView setContentOffset:CGPointMake(FScrollViewWidth, 0) animated:NO];
    //设置分页
    _scrollView.pagingEnabled=YES;
    //去掉滚动条
    _scrollView.showsHorizontalScrollIndicator=NO;
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(choseimage:)];
    [_scrollView addGestureRecognizer:tap];

}

-(void)choseimage:(UITapGestureRecognizer *)tap{
   NSLog(@"_currentImageIndex%ld",_currentImageIndex);
    
    if (_imagechick) {
        _imagechick(_imageData[_currentImageIndex],_currentImageIndex);
    }
    OpenUrlVC *urlVC = [[OpenUrlVC alloc]init];
  
  //  if (_Redirect.count>=_currentImageIndex) {
        urlVC.urlstr =_Redirect[_currentImageIndex];
        [self.navgationController pushViewController:urlVC animated:YES];

  //  }
    
}

#pragma mark 添加图片三个控件
-(void)addImageViews{
    _leftImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, FScrollViewWidth, FScrollViewHeight)];
    _leftImageView.contentMode=UIViewContentModeScaleAspectFill;
    
    [_scrollView addSubview:_leftImageView];
    _centerImageView=[[UIImageView alloc]initWithFrame:CGRectMake(FScrollViewWidth, 0, FScrollViewWidth, FScrollViewHeight)];
    _centerImageView.contentMode=UIViewContentModeScaleAspectFill;
    [_scrollView addSubview:_centerImageView];
    _rightImageView=[[UIImageView alloc]initWithFrame:CGRectMake(2*FScrollViewWidth, 0, FScrollViewWidth, FScrollViewHeight)];
    _rightImageView.contentMode=UIViewContentModeScaleAspectFill;
    [_scrollView addSubview:_rightImageView];
    
}
#pragma mark 设置默认显示图片
-(void)setDefaultImage{
    //加载默认图片

    if (_imageCount>1) {
      
        [_leftImageView sd_setImageWithURL:_imageData[_imageCount-1] placeholderImage:DefaultIMG options:SDWebImageRefreshCached];
        [_centerImageView sd_setImageWithURL:_imageData[0] placeholderImage:DefaultIMG]  ;// _imageData[0];
        [_rightImageView sd_setImageWithURL:_imageData[1] placeholderImage:DefaultIMG] ;
        

    }
    
       _currentImageIndex=0;
    //设置当前页
    
    _pageControl.currentPage=_currentImageIndex;
    
}

#pragma mark 添加分页控件
-(void)addPageControl{
    _pageControl=[[UIPageControl alloc]init];
    //注意此方法可以根据页数返回UIPageControl合适的大小
    CGSize size= [_pageControl sizeForNumberOfPages:_imageCount];
    _pageControl.bounds=CGRectMake(0, 0, size.width, size.height);
    _pageControl.center=CGPointMake(FScrollViewWidth/2, FScrollViewHeight-10);
    //设置颜色
    _pageControl.pageIndicatorTintColor=[UIColor colorWithRed:193/255.0 green:219/255.0 blue:249/255.0 alpha:1];
    //设置当前页颜色
    _pageControl.currentPageIndicatorTintColor=[UIColor colorWithRed:0 green:150/255.0 blue:1 alpha:1];
    //设置总页数
    _pageControl.numberOfPages=_imageCount;
    
    [self addSubview:_pageControl];
}

-(void)updateScrollView{
    BOOL needUpdate = NO;
    CGFloat offset_x = _scrollView.contentOffset.x;
    if (offset_x <= 0) {
        _currentImageIndex = [self processIndexWithIndex:_currentImageIndex -1];
        needUpdate = YES;
    }
    else if (offset_x >= 2*CGRectGetWidth(_scrollView.bounds)){
        _currentImageIndex = [self processIndexWithIndex:_currentImageIndex +1];
        needUpdate = YES;
    }
    if (!needUpdate) {
        return;
    }
    NSInteger leftIndex = [self processIndexWithIndex:_currentImageIndex -1];
    NSInteger rightIndex = [self processIndexWithIndex:_currentImageIndex +1];
    
    
    [_leftImageView sd_setImageWithURL:_imageData[leftIndex] placeholderImage:DefaultIMG options:SDWebImageRefreshCached];
    [_centerImageView sd_setImageWithURL:_imageData[_currentImageIndex] placeholderImage:DefaultIMG]  ;// _imageData[0];
    [_rightImageView sd_setImageWithURL:_imageData[rightIndex] placeholderImage:DefaultIMG] ;
    
    [_pageControl setCurrentPage:_currentImageIndex];
    [_scrollView setContentOffset:CGPointMake(CGRectGetWidth(_scrollView.bounds), 0)];
}

-(NSInteger)processIndexWithIndex:(NSInteger)index{
    if (index<0) {
        index = _imageCount -1;
    }else if (index > _imageCount -1){
        index = 0;
    }
    return index;
}




#pragma mark 滚动停止事件
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //重新加载图片
    [self reloadImage];
    //移动到中间
    [_scrollView setContentOffset:CGPointMake(FScrollViewWidth, 0) animated:NO];
    //设置分页
    _pageControl.currentPage=_currentImageIndex;
   
}

#pragma mark 重新加载图片
-(void)reloadImage{
    int leftImageIndex,rightImageIndex;
    CGPoint offset=[_scrollView contentOffset];
    if (offset.x>FScrollViewWidth) { //向右滑动
        _currentImageIndex=(_currentImageIndex+1)%_imageCount;
    }else if(offset.x<FScrollViewWidth){ //向左滑动
        _currentImageIndex=(_currentImageIndex+_imageCount-1)%_imageCount;
    }
    [_centerImageView sd_setImageWithURL:_imageData[_currentImageIndex] placeholderImage:DefaultIMG] ;
    
    //重新设置左右图片
    leftImageIndex=(_currentImageIndex+_imageCount-1)%_imageCount;
    rightImageIndex=(_currentImageIndex+1)%_imageCount;
    [_leftImageView  sd_setImageWithURL:_imageData[leftImageIndex] placeholderImage:DefaultIMG] ;
    [_rightImageView sd_setImageWithURL:_imageData[rightImageIndex] placeholderImage:DefaultIMG] ;
}





-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //  NSLog(@"%@",NSStringFromSelector(_cmd));
    [self updateScrollView];
    //分页控件
    [_pageControl setCurrentPage:_currentImageIndex];//滚动后当前页数也同时改变
    
}
//开始拖动
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //   NSLog(@"%@",NSStringFromSelector(_cmd));
    [_timer setFireDate:[NSDate distantFuture]];//停止
    
    
    
}
-(void)scrollViewDidScrollToTop:(UIScrollView *)scrollView{
    // NSLog(@"%@",NSStringFromSelector(_cmd));
}
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    //  NSLog(@"%@",NSStringFromSelector(_cmd));
}
//停止拖动
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    //   NSLog(@"%@",NSStringFromSelector(_cmd));
    [_timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];//延迟
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
